module.exports = function(app){
    app.controller('foodCtrl', function ($scope, $rootScope, $http, $modal, $interval) {
        
            window.updateFunc = function () { };
        
            $scope.orderByX = function (x) {
                console.log("call order by", x);
                $scope.orderBy = x;
            };
            $scope.filter = function () {
                console.log("call filter");
                $scope.search = $rootScope.search;
            };
        
            // 初始化，依赖�Merchant Ctrl
            $scope.init = function () {
                console.log("call food init()");
        
                $scope.types(); // 初始�Food Types
        
                $scope.merchant = $rootScope.merchant; // rootScope �Merchant 来自�Merchant Ctrl
                // if ($scope.merchant != undefined && $scope.merchant._id != undefined) {
                console.log('merchant', $scope.merchant)
                $scope.sync();   // 刷新菜品信息
                // } else {
                // console.log('wait 2s');
                // $interval(function () {
                //     console.log('sync after 2s');
                //     $scope.merchant = $rootScope.merchant;
                //     if ($scope.merchant != undefined && $scope.merchant._id != undefined) {
                //         console.log('merchant', $scope.merchant)
                //         $scope.sync();   // 刷新菜品信息
                //     }
                // }, 2000, 1);
                // }
            };
        
            // 初始�Food Types
            $scope.types = function () {
                console.log("call food foodtype()");
                $http({
                    method: 'GET',
                    url: 'foodtype'
                }).then(function successCallBack(res) {
                    console.log('callback food foodtype() success', res);
                    $rootScope.types = res.data.data;
                }, function errCallback(res) {
                    console.log('callback food foodtype() error', res);
                });
            };
        
            $scope.typeId2Name = function (id) {
                for (var i = 0; i < $rootScope.types.length; i++) {
                    if (id == $rootScope.types[i]._id) {
                        return $rootScope.types[i].typeName;
                    }
                }
            };
        
            // 同步菜品信息依赖 Merchant ID
            $scope.sync = function () {
                console.log("call food sync()");
                $http({
                    method: 'GET',
                    url: 'foods/byM'
                }).then(function successCallBack(res) {
                    console.log('callback sync() success', res);
                    $scope.foods = res.data.data;
                    // Food Type: ID -> Name
                        for (var i = 0; i < $scope.foods.length; i++) {
                            $scope.foods[i].foodType = $scope.typeId2Name($scope.foods[i].foodType);
                        }
                }, function errCallback(res) {
                    console.log('callback sync() error', res);
                });
            };
        
            // 呼出模态框
            $scope.add = function () {
                console.log("call add()");
                $scope.openAddModal();
            };
        
            // 呼出模态框，并自动填表
            $scope.edit = function (x) {
                console.log("call edit(", x, ")");
                // TODO 要改为在前端本地查找
                $http({
                    method: 'GET',
                    url: 'foods/' + x
                }).then(function successCallBack(res) {
                    // 请求成功将数据插入模态框
                    console.log('callback edit() success', res);
                    $scope.openUpdModal(res.data.data);
                }, function errCallback(res) {
                    console.log('callback edit() error', res);
                });
            };
        
            $scope.delete = function (x) {
                console.log("call delete(", x, ")");
                $http({
                    method: 'DELETE',
                    url: 'foods/' + x
                }).then(function successCallBack(res) {
                    console.log('callback delete() success', res);
                    $scope.sync();
                }, function errCallback(res) {
                    console.log('callback delete() error', res);
                });
            };
        
            $scope.openAddModal = function () {
                var modalInstance = $modal.open({
                    templateUrl: 'modal.html',
                    controller: 'addModalCtrl',
                    resolve: {
                        method: function () {
                            return $scope.sync;
                        },
                        data: function () {
                            // return $scope.merchant;
                            return $rootScope.merchant;
                        }
                    }
                });
            };
        
            $scope.openUpdModal = function (data) {
                var modalInstance = $modal.open({
                    templateUrl: 'modal.html',
                    controller: 'updModalCtrl',
                    resolve: {
                        method: function () {
                            return $scope.sync;
                        },
                        data: function () {
                            return data;
                        }
                    }
                });
            };
        });
        
        //模态框对应的Controller
        app.controller('addModalCtrl', function ($scope, $rootScope, $modalInstance, $http, method, data, FileUploader) {
        
            $scope.food = {};
            $scope.hide = true;
        
            $scope.init = function () {
                $scope.title = '新增菜品';
                $scope.method = method;
                $scope.types = $rootScope.types;
            }
        
            $scope.submit = function () {
                $scope.food.merchant = data._id;
                console.log("call add modal submit()", $scope.food);
                if ($scope.validateCompletion()) {
                    $http({
                        method: 'POST',
                        url: 'foods',
                        data: $scope.food,
                    }).then(function successCallBack(res) {
                        console.log('callback add modal submit() success', res);
                        $scope.method();
                        $modalInstance.close();
                    }, function errCallback(res) {
                        console.log('callback add modal submit() error', res);
                        alert("submit fail");
                    });
                }
            };
        
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        
            // warnning using DOM
            $scope.browse = function () {
                document.getElementById('file').click();
            };
        
            /* 上传图片 */
            // 上传控件
            $scope.uploader = new FileUploader({
                url: '/api/upload/foodpic',
                removeAfterUpload: true,
                queueLimit: 1
            });
        
            // 提交上传
            $scope.upload = function () {
                console.log("call upload");
                $scope.uploader.uploadAll();
            }
        
            // 上传完成执行此方�
            $scope.uploader.onCompleteItem = function (item, response, status, headers) {
                console.log("callback upload", response.path);
                $scope.food.foodPic = response.path;
                $scope.hide = false;
                alert("上传成功");
                $scope.validate.div.foodPic = '';
                $scope.validate.help.foodPic = '';
            }
            /* 上传图片 END*/
        
            /* 前端校验 */
            $scope.validate = {
                class: {
                    success: 'has-success has-feedback',
                    warnning: 'has-warning has-feedback',
                    error: 'has-error has-feedback',
                    successGlyphicon: 'glyphicon glyphicon-ok form-control-feedback',
                    warningGlyphicon: 'glyphicon glyphicon-warning-sign form-control-feedback',
                    errorGlyphicon: 'glyphicon glyphicon-remove form-control-feedback'
                },
                div: {},
                span: {},
                help: {}
            };
        
            $scope.validateCompletion = function () {
                var validate = true;
                if ($scope.food.foodName == undefined
                    || $scope.food.foodName == '') {
                    $scope.validate.div.foodName = $scope.validate.class.error;
                    $scope.validate.span.foodName = $scope.validate.class.errorGlyphicon;
                    $scope.validate.help.foodName = '菜品名称不能为空';
                    validate = false;
                }
                if ($scope.food.foodPrice == undefined
                    || $scope.food.foodPrice == '') {
                    $scope.validate.div.foodPrice = $scope.validate.class.error;
                    $scope.validate.span.foodPrice = $scope.validate.class.errorGlyphicon;
                    $scope.validate.help.foodPrice = '菜品价格不能为空';
                    validate = false;
                }
                if ($scope.food.foodPic == undefined
                    || $scope.food.foodPic == '') {
                    $scope.validate.div.foodPic = $scope.validate.class.error;
                    $scope.validate.help.foodPic = '请上传图片';
                    validate = false;
                }
                if ($scope.food.foodType == undefined
                    || $scope.food.foodPic == '') {
                    $scope.validate.div.foodType = $scope.validate.class.error;
                    $scope.validate.help.foodType = '请选择菜品类型';
                    validate = false;
                }
                return validate;
            };
        
            $scope.foodNameChange = function () {
                if ($scope.food.foodName == undefined
                    || $scope.food.foodName == '') {
                    $scope.validate.div.foodName = '';
                    $scope.validate.span.foodName = '';
                    $scope.validate.help.foodName = '';
        
                } else {
                    $scope.validate.div.foodName = $scope.validate.class.success;
                    $scope.validate.span.foodName = $scope.validate.class.successGlyphicon;
                    $scope.validate.help.foodName = '';
                }
            };
        
            $scope.foodPriceChange = function () {
                console.log($scope.food.foodPrice);
                if ($scope.food.foodPrice == undefined
                    || $scope.food.foodPrice == '') {
                    $scope.validate.div.foodPrice = '';
                    $scope.validate.span.foodPrice = '';
                    $scope.validate.help.foodPrice = '';
                } else {
                    $scope.validate.div.foodPrice = $scope.validate.class.success;
                    $scope.validate.span.foodPrice = $scope.validate.class.successGlyphicon;
                    $scope.validate.help.foodPrice = '';
                }
            };
        
            $scope.foodTypeChange = function () {
                console.log($scope.food.foodType);
                $scope.validate.div.foodType = '';
                $scope.validate.help.foodType = '';
        
            };
            /* 前端校验 END */
        });
        
        //模态框对应的Controller
        app.controller('updModalCtrl', function ($scope, $rootScope, $modalInstance, $http, method, data, FileUploader) {
        
            $scope.hide = false;
        
            $scope.init = function () {
                $scope.title = '编辑菜品';
                $scope.food = data;
                $scope.method = method;
                $scope.types = $rootScope.types;
            }
        
            $scope.submit = function () {
                console.log("call upd modal submit()", $scope.data);
                if ($scope.validateCompletion()) {
                    $http({
                        method: 'PUT',
                        url: 'foods',
                        data: $scope.food
                    }).then(function successCallBack(res) {
                        console.log('callback upd modal submit() success', res);
                        $scope.method();
                        $modalInstance.close();
                    }, function errCallback(res) {
                        console.log('callback upd modal submit() error', res);
                        alert("submit fail");
                    });
                }
            };
        
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            }
        
            /* 上传图片 START*/
        
            // warnning using DOM
            $scope.browse = function () {
                document.getElementById('file').click();
            };
        
            // 上传控件
            $scope.uploader = new FileUploader({
                url: '/api/upload/foodpic',
                removeAfterUpload: true,
                queueLimit: 1
            });
        
            // 提交上传
            $scope.upload = function () {
                console.log("call upload");
                $scope.uploader.uploadAll();
            }
        
            // 上传完成执行此方�
            $scope.uploader.onCompleteItem = function (item, response, status, headers) {
                console.log("callback upload", response.path);
                $scope.food.foodPic = response.path;
                alert("上传成功");
            }
            /* 上传图片 END*/
        
            /* 前端校验 */
            $scope.validate = {
                class: {
                    success: 'has-success has-feedback',
                    warnning: 'has-warning has-feedback',
                    error: 'has-error has-feedback',
                    successGlyphicon: 'glyphicon glyphicon-ok form-control-feedback',
                    warningGlyphicon: 'glyphicon glyphicon-warning-sign form-control-feedback',
                    errorGlyphicon: 'glyphicon glyphicon-remove form-control-feedback'
                },
                div: {},
                span: {},
                help: {}
            };
        
            $scope.validateCompletion = function () {
                var validate = true;
                if ($scope.food.foodName == undefined
                    || $scope.food.foodName == '') {
                    $scope.validate.div.foodName = $scope.validate.class.error;
                    $scope.validate.span.foodName = $scope.validate.class.errorGlyphicon;
                    $scope.validate.help.foodName = '菜品名称不能为空';
                    validate = false;
                }
                if ($scope.food.foodPrice == undefined
                    || $scope.food.foodPrice == '') {
                    $scope.validate.div.foodPrice = $scope.validate.class.error;
                    $scope.validate.span.foodPrice = $scope.validate.class.errorGlyphicon;
                    $scope.validate.help.foodPrice = '菜品价格不能为空';
                    validate = false;
                }
                return validate;
            };
        
            $scope.foodNameChange = function () {
                if ($scope.food.foodName == undefined
                    || $scope.food.foodName == '') {
                    $scope.validate.div.foodName = '';
                    $scope.validate.span.foodName = '';
                    $scope.validate.help.foodName = '';
        
                } else {
                    $scope.validate.div.foodName = $scope.validate.class.success;
                    $scope.validate.span.foodName = $scope.validate.class.successGlyphicon;
                    $scope.validate.help.foodName = '';
                }
            };
        
            $scope.foodPriceChange = function () {
                console.log($scope.food.foodPrice);
                if ($scope.food.foodPrice == undefined
                    || $scope.food.foodPrice == '') {
                    $scope.validate.div.foodPrice = '';
                    $scope.validate.span.foodPrice = '';
                    $scope.validate.help.foodPrice = '';
                } else {
                    $scope.validate.div.foodPrice = $scope.validate.class.success;
                    $scope.validate.span.foodPrice = $scope.validate.class.successGlyphicon;
                    $scope.validate.help.foodPrice = '';
                }
            };
        });
}

